using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using TakeAway.DataSet;

namespace TakeAway.Controls
{
    public partial class FilterClientXtraForm : XtraForm
    {
        
        private Controller _controller;
        private bool _modify;

        public Controller Controller { set { _controller = value; } }

        public bool Modify { set { _modify = value; } }


        public FilterClientXtraForm()
        {
            InitializeComponent();
            searchSimpleButton.Click += SearchSimpleButtonClick;
            gridView.DoubleClick += GridViewDoubleClick;
            okSimpleButton.Click += OKSimpleButtonClick;
        }

        private void ReturnClient(long clientNumber)
        {
            _controller.ShowClient(_modify, clientNumber);
            DialogResult = DialogResult.OK;
            Close();
        }

        void OKSimpleButtonClick(object sender, EventArgs e)
        {
            var client = (ClienteDataSet.ClienteRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (client == null)
                _controller.NewClient(_modify, nameTextEdit.Text, phoneTextEdit.Text, fiscalNumberTextEdit.Text, streetTextEdit.Text);
            else
                _controller.ShowClient(_modify, client.Numero);
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var client = (ClienteDataSet.ClienteRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (client == null)
                return;
            ReturnClient(client.Numero);
        }

        void SearchSimpleButtonClick(object sender, EventArgs e)
        {
            gridView.BeginUpdate();
            var dataSet = _controller.GetClients(nameTextEdit.Text, phoneTextEdit.Text, fiscalNumberTextEdit.Text, streetTextEdit.Text);
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Cliente.TableName;
            gridView.EndUpdate();
            if (dataSet.Cliente.Count == 1)
                ReturnClient(dataSet.Cliente[0].Numero);
        }
    }
}